package coder.nav.utils;

import cn.hutool.core.date.DateUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 爬虫获取日历信息
 * @author Bosen 2025/4/11 17:30
 */
public class MsnUtils {

    public static Map<String, Element> getCalendar(Date date) {
        String url = "https://cn.bing.com/richcalendar/fetch?year=" + DateUtil.year(date) + "&month=" + (DateUtil.month(date) + 1) + "&day=" + DateUtil.dayOfMonth(date);
        try {
            Document document = Jsoup.connect(url).get();
            Elements rcldCells = document.getElementsByClass("rcld_cell");
            return rcldCells.stream().collect(Collectors.toMap(item -> item.attr("data-date"), Function.identity(), (k1, k2) -> k1));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static boolean isWork(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        boolean isWork = false;
        Map<String, Element> calendar = getCalendar(date);
        Element rcldCell = calendar.get(sdf.format(date));
        if(Objects.isNull(rcldCell)) {
            return isWork;
        }
        Elements rcldCelllabels = rcldCell.getElementsByClass("rcld_celllabel");
        if(CollectionUtils.isEmpty(rcldCelllabels)) {
            int dayOfWeek = DateUtil.dayOfWeek(date);
            isWork = dayOfWeek > 1 && dayOfWeek < 7;
        } else {
            String rcldCelllabelText = rcldCelllabels.stream().findFirst().get().text().trim();
            isWork = "班".equals(rcldCelllabelText);
        }
        return isWork;
    }

}
